﻿using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
using Architecture.Repository;
using Architecture.Repository.Impl;
using Architecture.Repository.Interface;
using Architecture.Domain.Services;
using Architecture.Common;

namespace Architecture.Api.Extensions
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 注册数据库
        /// </summary>
        /// <typeparam name="TDbContext">EF上下文</typeparam>
        /// <param name="services">扩展的类型</param>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="enableSqlLog">是否打印执行EF语句转义的sql</param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<TDbContext>(this IServiceCollection services, string? connectionString, bool enableSqlLog) where TDbContext : DbContext
        {
            return services.AddDbContext<TDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        errorNumbersToAdd: null);
                }).EnableSensitiveDataLogging();
                if (enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure
                        .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        .AddConsole();
                    }));
                }
            });
        }

        /// <summary>
        /// 注册JWT
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="builder"></param>
        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
               .AddJwtBearer(options =>
               {
                   //取出私钥
                   var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                   options.TokenValidationParameters = new TokenValidationParameters()
                   {
                       //验证发布者
                       ValidateIssuer = true,
                       ValidIssuer = builder.Configuration["Authentication:Issuer"],
                       //验证接收者
                       ValidateAudience = true,
                       ValidAudience = builder.Configuration["Authentication:Audience"],
                       //验证是否过期
                       ValidateLifetime = true,
                       //验证私钥
                       IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                   };
               });

        }
        
        ///依赖注入扩展类        
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddScoped<EFCoreContext>();
            services.AddScoped<IRoleService, RoleService>();
            services.AddScoped<IRoleRepository, RoleRepository>();
            services.AddScoped<IUserInfoRepository, UserInfoRepository>();
            services.AddScoped<IUserInfoService, UserInfoService>();
            services.AddScoped<IdentityUser>();
            services.AddScoped<JwtTools>();
            return services;
        }
    }
}
